<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-07 15:13:14
 * @Last Modified time: 2023-02-16 15:24:32
 */
namespace app\common\services\store\order;

use app\common\dao\store\OrderDao;
use think\facade\Db;

use frank\base\BaseService;
use frank\exception\CommonException;

use app\common\enum\pay\PayTypeEnum;
use app\common\factory\store\goods\source\Factory as StockFactory;
use app\common\enum\store\order\SourceEnum;
use app\common\enum\user\WaterSourceEnum;
use app\common\services\user\UserWaterService;
use app\common\services\store\OrderDeliveryService;
/**
 * Class PaySuccessService
 */
class PaySuccessService extends BaseService
{

    // 订单
    public $detail;

    // 当前用户信息
    private $user;

    /**
     * PaySuccessService constructor.
     * @param OrderDao $dao
     */
    public function __construct(OrderDao $dao,$orderNo)
    {
        $this->dao = $dao;
        // 实例化订单模型
        $this->detail = $this->dao->getOrderPayDetail($orderNo);
        if (is_null($this->detail)) {
            throw new CommonException('订单不存在');
        } 
        // 获取用户信息
        $this->user = $this->detail['user_detail'];
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetail()
    {
        return $this->detail;
    }

      /**
     * 订单支付成功业务处理
     */
    public function onPaySuccess($payType, $payData = [])
    {
        if (empty($this->detail)) {
            $this->error = '未找到该订单信息';
            return false;
        }
        // 更新付款状态
        $status = $this->updatePayStatus($payType, $payData);
        // 支付成功
        if ($status) {
            // 发送消息
            // helper::sendMsg($this->user['wxapp_openid'],$this->model);
            // 小票打印
        }
        return $status;
    }

    /**
     * 更新付款状态
     */
    private function updatePayStatus($payType, $payData = [])
    {
        // 事务处理
        $status =  $this->updateOrderInfo($payType, $payData);
        // 更新订单状态
        return  $status;
    }


    /**
     * 更新订单记录
     */
    private function updateOrderInfo($payType, $payData)
    {
        // 验证余额支付时用户余额是否满足
        if ($payType == PayTypeEnum::WALLET) {
            if ($this->user['balance'] < $this->detail['order_pay_price']) {
                $this->error = '用户余额不足，无法使用余额支付';
                return false;
            }
        }
        // 创建新的订单
        Db::startTrans();
        try {
            // 更新商品库存、销量
            StockFactory::getFactory($this->detail['order_source']['value'])->updateStockSales($this->detail['goods'],$this->detail['order_source_id']);

            // 整理订单信息
            $order = [
                'pay_price' => $payData['pay_price'],
                'pay_type' => $payType,
                'pay_status' => 1,
                'pay_time' => time(),
                'order_id'=>$this->detail['id']
            ];

            $water = [
                'pay_type'=>$payType,
                'soure_id' => $this->detail['order_id'],
                'user_id' => $this->user['id'],
                'money' => -$payData['pay_price'],
            ];

            // 微信支付
            if ($payType == PayTypeEnum::WECHAT) {
                $order['pay_transaction'] = $payData['transaction_id'];
                $order['pay_price'] = $payData['pay_price'];
                 // WxappPrepayIdM::updatePayStatus($this->detail['order_id'], SourceEnum::MASTER);
            }
            // 余额支付
            if ($payType == PayTypeEnum::WALLET) {
                // 更新用户余额
                $this->user->dec('balance', $payData['pay_price'])->update();
                $water['user_balance'] = $this->user->balance - $payData['pay_price'];
            }

            // 记录用户流水
            UserWaterService::instance()->createWater(WaterSourceEnum::ORDERPAY,$water, ['order_no' => $this->detail['order_no']] );

            // 创建订单物流详细
            OrderDeliveryService::instance()->createDelivery($this->detail['goods'],$this->detail['delivery_type']['value']);


            // 更新订单状态
            $this->detail->save($order);

            // 提交事务
            Db::commit();
            return true;
        } catch (Exception $e) {
            $this->error = $e->getMessage() ?? '';
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
}